package com.heimali.sf;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.heimali.sf.config.CommonConfig;
import com.heimali.sf.config.Constants;
import com.heimali.sf.fragments.AppFeeFragment;
import com.heimali.sf.fragments.BaseFragment;
import com.heimali.sf.fragments.CalendarFragment;
import com.heimali.sf.fragments.RegFeeFragment;
import com.heimali.sf.models.UpdateInfo;
import com.heimali.sf.utils.AndroidUtils;
import com.heimali.sf.utils.SystemUtils;
import com.heimali.sf.wraper.BaseWraper;
import com.heimali.sf.wraper.UpdateWraper;

public class HomeActivity extends FragmentActivity implements OnClickListener {

	public static final String TAG = "HomeActivity";

	public enum ShowType {
		RegFee, AppFee, Calendar
	};

	public ShowType mCurShowType = null;

	public ViewPager mViewPager;
	private Button mRegFeeTabBtn; // 受理费
	private Button mAppFeeTabBtn; // 申请费
	private Button mCalendarTabBtn; //日历
	private RegFeeFragment mRegFeeFragment;
	private AppFeeFragment mAppFeeFragment;
	private CalendarFragment mCalendarFragment;
	private ArrayList<Fragment> mFragmentList;

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		initView();
		initViewPager();
		autoCheckNewVersion();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void initView() {
		mRegFeeTabBtn = (Button) findViewById(R.id.tab_reg_fee);
		mRegFeeTabBtn.setOnClickListener(this);
		mAppFeeTabBtn = (Button) findViewById(R.id.tab_app_fee);
		mAppFeeTabBtn.setOnClickListener(this);
		mCalendarTabBtn = (Button) findViewById(R.id.tab_calendar);
		mCalendarTabBtn.setOnClickListener(this);

		mViewPager = (ViewPager) findViewById(R.id.view_pager);
	}

	private void initViewPager() {
		mRegFeeFragment = new RegFeeFragment();
		mFragmentList = new ArrayList<Fragment>();
		mFragmentList.add(mRegFeeFragment);
		mAppFeeFragment = new AppFeeFragment();
		mFragmentList.add(mAppFeeFragment);
		mCalendarFragment = new CalendarFragment();
		mFragmentList.add(mCalendarFragment);
		mViewPager.setAdapter(new HomeFragmentPagerAdapter(mFragmentList));
		mViewPager.setOnPageChangeListener(new HomeOnPageChangeListener());
		mViewPager.setOffscreenPageLimit(2);
	}

	/**
	 * 根据类型返回对应索引值
	 * 
	 * @param type
	 * @return
	 */
	public static int findIndexByType(ShowType type) {
		if (ShowType.RegFee == type) {
			return 0;
		} else if (ShowType.AppFee == type) {
			return 1;
		} else if (ShowType.Calendar == type) {
			return 2;
		} else {
			return -1;
		}
	}

	/**
	 * 根据索引返回对应类型
	 * 
	 * @param index
	 * @return
	 */
	public static ShowType findTypeByIndex(int index) {
		switch (index) {
		case 1:
			return ShowType.AppFee;
		case 2:
			return ShowType.Calendar;
		default:
			return ShowType.RegFee;
		}
	}

	/**
	 * 切换Fragment
	 * 
	 * @param type
	 */
	public void changeFragment(ShowType type) {
		BaseFragment.lastExitTime = 0;

		mRegFeeTabBtn.setBackgroundDrawable(null);
		mAppFeeTabBtn.setBackgroundDrawable(null);
		mCalendarTabBtn.setBackgroundDrawable(null);

		int tabHighLightBgColor = getResources().getColor(R.color.tab_bg_highlight);
		if (type == ShowType.RegFee) {
			mRegFeeTabBtn.setBackgroundColor(tabHighLightBgColor);
		} else if (type == ShowType.AppFee) {
			mAppFeeTabBtn.setBackgroundColor(tabHighLightBgColor);
		} else if (type == ShowType.Calendar) {
			mCalendarTabBtn.setBackgroundColor(tabHighLightBgColor);
		}

		mCurShowType = type;

		if (type == ShowType.RegFee) {
			mRegFeeFragment.refreshUI();
		} else if (type == ShowType.AppFee) {
			mAppFeeFragment.refreshUI();
		} else if (type == ShowType.Calendar) {
			mCalendarFragment.refreshUI();
		}
	}

	public class HomeFragmentPagerAdapter extends FragmentPagerAdapter {
		private ArrayList<Fragment> fragmentsList;

		public HomeFragmentPagerAdapter(ArrayList<Fragment> fragments) {
			super(getSupportFragmentManager());
			this.fragmentsList = fragments;
		}

		@Override
		public int getCount() {
			return fragmentsList.size();
		}

		@Override
		public Fragment getItem(int arg0) {
			return fragmentsList.get(arg0);
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}
	}

	public class HomeOnPageChangeListener implements OnPageChangeListener {

		public void onPageSelected(int index) {
			switch (index) {
			case 0:
				changeFragment(ShowType.RegFee);
				break;
			case 1:
				changeFragment(ShowType.AppFee);
				break;
			case 2:
				changeFragment(ShowType.Calendar);
				break;
			}
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		public void onPageScrollStateChanged(int index) {
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tab_reg_fee:
			if (mCurShowType == ShowType.RegFee)
				return;
			mViewPager.setCurrentItem(findIndexByType(ShowType.RegFee));
			break;
		case R.id.tab_app_fee:
			if (mCurShowType == ShowType.AppFee)
				return;
			mViewPager.setCurrentItem(findIndexByType(ShowType.AppFee));
			break;
		case R.id.tab_calendar:
			if (mCurShowType == ShowType.Calendar)
				return;
			mViewPager.setCurrentItem(findIndexByType(ShowType.Calendar));
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		menu.add(Menu.NONE, R.id.menu_about, Menu.NONE, R.string.menu_about);
		menu.add(Menu.NONE, R.id.menu_exit, Menu.NONE, R.string.menu_exit);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_about:
			showAboutDialog(HomeActivity.this);
			break;
		case R.id.menu_exit:
			finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public static void showAboutDialog(Context cxt) {
		AlertDialog.Builder aa = new AlertDialog.Builder(cxt);
		View aalayout = View.inflate(cxt, R.layout.dialog_about, null);
		((TextView) aalayout.findViewById(R.id.about_app_name)).setText(cxt.getString(R.string.about_message_1,
				cxt.getString(R.string.app_name)));
		((TextView) aalayout.findViewById(R.id.about_version_info)).setText(cxt.getString(R.string.about_message_2,
				AndroidUtils.getVersionName()));
		((TextView) aalayout.findViewById(R.id.about_copyright_info)).setText(cxt.getString(R.string.about_message_3,
				Calendar.getInstance().get(Calendar.YEAR)));
		aa.setCancelable(true);
		aa.setTitle(R.string.about_title);
		aa.setView(aalayout);
		aa.setNegativeButton(cxt.getString(R.string.btn_ok), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialoginterface, int i) {
			}
		});
		AlertDialog dii = aa.create();
		dii.show();
	}
	
	/**
	 * 自动检查新版本
	 */
	protected void autoCheckNewVersion() {
		final String today = SystemUtils.getCurrentDate();
		String lastCheckTime = CommonConfig.getInstance().getConfig(Constants.COMMON_CONFIG_LAST_CHECK_UPDATE_TIME, "");
		if (today.equals(lastCheckTime)) {
			return ;
		}
		
		new UpdateWraper(new BaseWraper.Callback() {
			public void onSuccess(Object result) {
				setLastCheckUpdateTime(today);
				int versionCode = SystemUtils.getVersionCode();
				UpdateInfo info = (UpdateInfo) result;
				if (info.minVerCode > versionCode) {
					forceUpdate(info);
				}else if (info.verCode > versionCode) {
					confirmUpdate(info);
				}
			}
			
			public void onFail(int errno, String errmsg) {
				setLastCheckUpdateTime(today);
			}
		}).execute();
	}
	
	/**
	 * 设置最后检查更新时间
	 * @param today
	 */
	private void setLastCheckUpdateTime(String today) {
		CommonConfig.getInstance().setConfig(Constants.COMMON_CONFIG_LAST_CHECK_UPDATE_TIME, today);
	}
	
	/**
	 * 强制升级到最低版本的升级方式
	 * @param info
	 */
	private void forceUpdate(UpdateInfo info) {
		
	}
	
	/**
	 * 需要确认的升级方式
	 * @param info
	 */
	private void confirmUpdate(final UpdateInfo info) {
		String msg = getString(R.string.update_msg_normal_update, info.verName);
		String updates = getString(R.string.update_msg_normal_update_title, info.verName);
		
		AlertDialog.Builder builder = new Builder(this);
		builder.setIcon(android.R.drawable.ic_dialog_info)
		.setTitle(R.string.tip)
		.setMessage(msg + "\n\n" + updates + "\n" + info.description + "\n")
		.setPositiveButton(R.string.update_now, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse(info.url));
				startActivity(intent);
			}
		}).setNegativeButton(R.string.update_skip, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
			}
		}).create().show();
	}
}